package com.hcloud.common.social.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hcloud.common.social.config.QqConfig;
import com.hcloud.common.social.config.SocialRestTemplate;
import com.hcloud.common.social.config.WeixinConfig;
import com.hcloud.common.social.exception.WrongGiteeCodeException;
import com.hcloud.common.social.exception.WrongQQCodeException;
import com.hcloud.common.social.exception.WrongWeixinCodeException;
import com.hcloud.common.social.service.QQInfoService;
import com.hcloud.common.social.service.WeixinInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Map;

/**
 * @Auther hepangui
 * @Date 2018/12/13
 */
@Slf4j
@Service
public class QQInfoServiceImpl implements QQInfoService {

    private final String TOKEN_URL = "https://graph.qq.com/oauth2.0/token" +
            "?code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}&grant_type=authorization_code";

    private final String INFO_URL = "https://graph.qq.com/oauth2.0/me?access_token={access_token}";
    @Autowired
    private QqConfig qqConfig;

    @Override
    public String getOpenId(String code) {
        try{
            String result = SocialRestTemplate.getRestTemplate().getForObject(TOKEN_URL.replace("{client_id}", qqConfig.getAppId())
                            .replace("{redirect_uri}", qqConfig.getRedirectUri())
                            .replace("{client_secret}", qqConfig.getAppSecret()).replace("{code}", code),
                    String.class
            );
            log.info(result);//access_token=B865C7E3FF8A01AA6E9F47E875BDE534&expires_in=7776000&refresh_token=6A0AAC38A471D440B726FF093B7E6BA4
            if(result!=null && result.indexOf("access_token=")>-1){
                int i = result.indexOf("access_token=");
                String accessToken = result.substring(i+"access_token=".length(),result.indexOf("&",i));
                result =  SocialRestTemplate.getRestTemplate().getForObject(INFO_URL.replace("{access_token}",accessToken),
                        String.class);
                System.out.println(result);
                //callback( {"client_id":"101535094","openid":"E35A97C1F900B77EE8C58118F7F7B828"} );
                Map map = JSONObject.parseObject(result.substring(result.indexOf("{"),result.indexOf("}")+1),Map.class);

                return (String)(map.get("openid"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        throw new WrongQQCodeException();

    }
}
